//
//  Status.swift
//  LX_weibo
//
//  Created by LTT❤️ on 15/7/4.
//  Copyright © 2015年 LTT. All rights reserved.
//

import UIKit
import SDWebImage


//首页URL
private  let WB_HomeLine_URL = "2/statuses/home_timeline.json"



class Status: NSObject {
    //微博创建时间
    var created_at:String?
    //微博ID
    var id:Int = 0
    //微博信息内容
    var text:String?
    //微博来源
    var source:String?
    //图片数组
    var pic_urls:[[String:String]]?
    {
        didSet {
            //设置 imageURLs的数组
            imageURLs = [NSURL]()
            for  dict in pic_urls!{
                let  urlString = dict["thumbnail_pic"]!
                imageURLs?.append(NSURL(string: urlString)!)
            }
            
            
        }
        
    }
    //图片的URL数组
    private var imageURLs:[NSURL]?
    
    
    var picURLs:[NSURL]?{
        return retweeted_status != nil ? retweeted_status?.imageURLs:imageURLs
    }
    
    
    
    
    //用户模型
    var user:User?
    //转发
    var retweeted_status: Status?
    
    static let properties = ["created_at","id","text","source","pic_urls","user","retweeted_status"]
    //字典转模型
    init(dict: [String:AnyObject]){
        super.init()
        for key in Status.properties{
            if dict[key] == nil || key == "user" || key == "retweeted_status" {
                continue
            }
                setValue(dict[key], forKey: key)
        }
        
        if let userDict = dict["user"] as? [String: AnyObject]
        {
            user = User(dict: userDict)
        }
        //判断字典中是否包含retweeted_status
        if let retweetedDict = dict["retweeted_status"] as? [String:AnyObject]{
            retweeted_status = Status(dict:retweetedDict)
        }
        
    }
    
    //打印
    override var description : String{
        let dict = dictionaryWithValuesForKeys(Status.properties)
        return "\(dict)"
        
    }
    
    
    
    
    //加载数据
    class func loadStatus(since_id:Int,finished:(statuses:[Status]?,error:NSError?)->()){
        //断言
        assert(sharedUserAccount != nil,"必须登录之后才能访问网络")
        
        var params = ["access_token":sharedUserAccount!.access_token]
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
            
        }
        
        
        //发起网络请求 ,异步加载数据
        NetworkTools.sharedNetworkTools().GET(WB_HomeLine_URL, parameters: params, success: { (_, JSON) -> Void in

            print(JSON)
            //从结果中获取数组
          if  let array = JSON["statuses"] as? [[String:AnyObject]]
          {
            //获得数组
            let list = statuses(array)
            //异步缓存
            cacheWebImage(list,finished:finished)
            return
            }
            //回调空值,解析失败其他原因
            finished(statuses: nil, error: nil)
            
            }) { (_, error) -> Void in
                print(error)
                finished(statuses: nil, error: error)
        }
        
        
    }
    
    ///缓存微博数组中的所有图像
    private class func cacheWebImage(list :[Status],finished:(statuses:[Status]?,error:NSError?)->()){
       //调度组
        let group =  dispatch_group_create()
        
        //遍历数组
        for s in list
        {
            if s.picURLs == nil || s.picURLs!.isEmpty
            {
                continue
            }
           //遍历imageURLs数组
            for url in s.picURLs!
            {
                //进入组,后续的block 会监听
                dispatch_group_enter(group)
                //单例用来维护缓存和下载
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue:0), progress: nil, completed:
                    { (_, _, _, _, _) -> Void in
                //打印应用程序路径
                    print(NSHomeDirectory())
                    
                    //离开祖
                    dispatch_group_leave(group)
                    })
            }
          
        }
         //监听群组调度执行
            dispatch_group_notify(group, dispatch_get_main_queue(), {
                finished(statuses: list,error:nil)
            })
    }
    
    
    
    private class func statuses (Array:[[String:AnyObject]]) ->[Status]{
        //定义可变数组
        var  arrayM = [Status]()
        //遍历array
        for dict in Array{
            
            arrayM.append(Status(dict: dict))
        }
        return arrayM

    }

}
